package gern;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.text.SimpleDateFormat;
import java.util.Date;

public class DemoUtil {


    public static <T> String printMeaning(T t) {
        String meaning = "--------------hello this is my meaning ---------------\n";
        String[] fieldNames = getFiledName(t);
        for (int i = 0; i < fieldNames.length; i++) {
            String name = fieldNames[i];
            Object value = getFieldValueByName(name, t);
            if (null != value) {
                if (getFiledType(name, t).equals(Date.class)) {
                    value = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format((Date) value);
                }
                meaning += "-" + (name + " : " + value) + "\n";
            }
        }

        System.out.println(meaning);
        return meaning;
    }

    private static String[] getFiledName(Object o) {
        Field[] fields = o.getClass().getDeclaredFields();
        String[] fieldNames = new String[fields.length];
        for (int i = 0; i < fields.length; i++) {
            fieldNames[i] = fields[i].getName();
        }
        return fieldNames;
    }


    private static Object getFieldValueByName(String fieldName, Object o) {
        try {
            String firstLetter = fieldName.substring(0, 1).toUpperCase();
            String getter = "get" + firstLetter + fieldName.substring(1);
            Method method = o.getClass().getMethod(getter, new Class[]{});
            Object value = method.invoke(o, new Object[]{});
            return value;
        } catch (Exception e) {
            System.out.println("获取属性值失败！");
        }
        return null;
    }

    /**
     * @param fieldName
     * @param o
     * @return
     * @desc 获取属性的数据类型
     */
    public static Object getFiledType(String fieldName, Object o) {
        Field[] fields = o.getClass().getDeclaredFields();
        for (Field field : fields) {
            if (fieldName.equals(field.getName())) {
                return field.getType();
            }
        }
        return null;
    }


}
